package com.bianxingji.utils;


import org.json.JSONArray;
import org.json.JSONObject;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.LinkedList;

/**
 * @author: 24478
 * @create: 2024-12-11 18:09
 **/
public class GetData {

    public class MyData{
        private String name;
        private String showTime;
        private String movieImg;
        private String movieStarImg;

        public MyData(String name, String showTime, String movieImg, String movieStarImg) {
            this.name = name;
            this.showTime = showTime;
            this.movieImg = movieImg;
            this.movieStarImg = movieStarImg;
        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public String getShowTime() {
            return showTime;
        }

        public void setShowTime(String showTime) {
            this.showTime = showTime;
        }

        public String getMovieImg() {
            return movieImg;
        }

        public void setMovieImg(String movieImg) {
            this.movieImg = movieImg;
        }

        public String getMovieStarImg() {
            return movieStarImg;
        }

        public void setMovieStarImg(String movieStarImg) {
            this.movieStarImg = movieStarImg;
        }
    }

    //拿到变形计的集数介绍和图片信息
    public static  HashMap<String, LinkedList<MyData>> getQI() {
        String baseUrl = "https://pcweb.api.mgtv.com/list/master?_support=10000000&vid=&cid={cid}&pn=1&ps=60&platform=4&src=mgtv&allowedRC=1";
        String detailUrl = "https://pcweb.api.mgtv.com/player/vinfo?video_id={video_id}&cid={cid}&pid=&cxid=8kpqp21m4cm&entranceType=0&_support=10000000&allowedRC=1";
        String initialUrl = baseUrl.replace("{cid}", "294541"); // 初始请求的 cid
        StringBuilder resultBuilder = new StringBuilder();

        String[] quarter = new String[]{"第一季","第二季","第三季","第四季","第五季","第六季","第七季","第八季"};
        HashMap<String, LinkedList<MyData>> stringLinkedListHashMap = new HashMap<>();
        try {
            // Step 1: 请求初始地址，获取 tab_y 集合
            JSONObject initialResponse = getJsonResponse(initialUrl);
            JSONArray tabY = initialResponse.getJSONObject("data").getJSONArray("tab_y");

            // Step 2: 遍历 tab_y 集合中的 id，分别请求各季数据
            for (int i = tabY.length()-1; i > 9; i--) {
                LinkedList<MyData> myData = new LinkedList<>();
                JSONObject season = tabY.getJSONObject(i);
                String cid = season.getString("id");
                String seasonUrl = baseUrl.replace("{cid}", cid);

                // 请求该季数据
                JSONObject seasonResponse = getJsonResponse(seasonUrl);
                JSONArray videoList = seasonResponse.getJSONObject("data").getJSONArray("list");

                // 提取视频信息
                resultBuilder.append("季度：").append("第"+(tabY.length()-i)+"季").append("\n");
                for (int j = 0; j < videoList.length(); j++) {
                    JSONObject video = videoList.getJSONObject(j);
                    String img = video.getString("img");
                    String time = video.getString("time");
                    String t3 = video.getString("t3");
                    String videoId = video.getString("video_id");

                    // 请求视频详细信息
                    String detailedUrl = detailUrl.replace("{video_id}", videoId).replace("{cid}", cid);
                    JSONObject detailResponse = getJsonResponse(detailedUrl);
                    String clipImgUrl2 = detailResponse.getJSONObject("data").getString("clip_imgurl2");
                    MyData myData2 = new GetData().new MyData(t3, time, img, clipImgUrl2);

                    resultBuilder.append("Video Name: ").append(t3).append("\n");
                    resultBuilder.append("Video Time: ").append(time).append("\n");
                    resultBuilder.append("Video Cover: ").append(img).append("\n");
                    resultBuilder.append("Clip Img URL 2: ").append(clipImgUrl2).append("\n");
                    resultBuilder.append("----------------------------------\n");
                    myData.add(myData2);

                }
                stringLinkedListHashMap.put(quarter[tabY.length()-i-1],myData);
                resultBuilder.append("\n");
            }

            // Step 3: 输出到桌面 d.txt 文件
            File outputFile = new File( "D://desktop/d.txt");
            try (BufferedWriter writer = new BufferedWriter(new FileWriter(outputFile))) {
                writer.write(resultBuilder.toString());
                System.out.println("数据已写入到: " + outputFile.getAbsolutePath());
                System.out.println(stringLinkedListHashMap);
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return stringLinkedListHashMap;
    }

    // 发送 HTTP 请求并解析响应为 JSONObject
    private static JSONObject getJsonResponse(String urlString) throws Exception {
        URL url = new URL(urlString);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("GET");
        connection.setRequestProperty("User-Agent", "Mozilla/5.0");

        BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        String inputLine;
        StringBuilder response = new StringBuilder();

        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine);
        }
        in.close();

        return new JSONObject(response.toString());
    }
}
